package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.constat.MessageConstant;
import com.itheima.constat.RedisConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @authou: fu
 * @date:Created in 2019/12/7
 * @description: 发送验证码
 * @version:1.0
 */
@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {

    @Autowired
    private JedisPool jedisPool;

    //用户在线发送验证码
    @RequestMapping("/send4Order")
    public Result send4Order(String telephone){
        //获取一个6位数的验证码
        String validateCode = ValidateCodeUtils.generateValidateCode(6).toString();
        //使用阿里云工具类发送验证码
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,validateCode);
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        Jedis jedis = jedisPool.getResource();

        jedis.setex(telephone + RedisConstant.SENDTYPE_ORDER,300,validateCode);
        jedis.close();

        return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }


    //用户在线发送验证码
    @RequestMapping("/send4Login")
    public Result send4Login(String telephone){
        //获取一个6位数的验证码
        String validateCode = ValidateCodeUtils.generateValidateCode(6).toString();
        //使用阿里云工具类发送验证码
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,validateCode);
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        Jedis jedis = jedisPool.getResource();

        jedis.setex(telephone + RedisConstant.SENDTYPE_LOGIN,300,validateCode);
        jedis.close();

        return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }
}
